import { pickedFaceData, pickedLineData } from '@amcax/base';
import i18n from '@app-cad/common/utils/i18next';
import { NMTopoBaseCommand } from '@app-cad/environments/nextmesh/types/command';

import { ModifyMode, TopoDialogProps } from '../type';
import { useState } from 'react';

import { documentV2 } from '@app-nextmesh/domain';

import { useCommand } from '@app-base/common/hooks/useCommand';

import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { PickInputRJSFFormat } from '@app-base/common/components/command-form/constants';

import { PickableCommandForm } from '@app-base/common/components/command-form/pickable';

type FormData = {
  edge: pickedLineData;
  face: pickedFaceData;
};
function TopoModifyDialog({ title, onClose }: TopoDialogProps) {
  const [formData, setFormData] = useState<FormData>({
    edge: null,
    face: null,
  });
  useCommand('cmdTopoModify', {
    onClose,
  });
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      face: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
        uniqueItems: true,
      },
      edge: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
        uniqueItems: true,
      },
    },
  };
  const uiSchema: UiSchema = {
    face: {
      'ui:placeholder': '请选择修改的面',
      'ui:autofocus': true,
    },
    edge: {
      'ui:placeholder': '请输入需要修改的边',
    },
  };
  const isValid = () => {
    const { edge, face } = formData;
    return edge !== null && face !== null;
  };
  const handleSubmit = async () => {
    if (!isValid()) {
      return;
    }
    const { edge, face } = formData;
    await documentV2.modifyEntity({
      mode: ModifyMode.AlongFace,
      source: [edge.edgeId],
      target: [face.meshId],
    });
  };
  return (
    <PickableCommandForm
      schema={schema}
      title={title}
      onClose={onClose}
      extraUiSchema={uiSchema}
      isFormDataValid={isValid()}
      formData={formData}
      onChange={(data) => {
        setFormData(data);
      }}
      onSubmit={handleSubmit}></PickableCommandForm>
  );
}
export const cmdTopoModify: NMTopoBaseCommand = {
  id: 'cmdTopoModify',
  icon: 'commands/curved/point',
  label: 'command.topo.modify',
  create: (label: string, onClose: () => void, props) => (
    <TopoModifyDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
